package top.majuan.springboot3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.majuan.springboot3.base.PageBean;
import top.majuan.springboot3.base.R;
import top.majuan.springboot3.dao.TbGameMapper;
import top.majuan.springboot3.dao.TbGamepublisherMapper;
import top.majuan.springboot3.entity.TbGame;
import top.majuan.springboot3.entity.TbGamepublisher;
import top.majuan.springboot3.service.TbGameService;
import top.majuan.springboot3.vo.PageVo;

@Service
@Slf4j
@RequiredArgsConstructor
public class TbGameServiceImpl implements TbGameService {
    public final TbGameMapper tbGameMapper;
    public final TbGamepublisherMapper tbGamepublisherMapper;

    @Override
    public R<String> insert(TbGame tbGame) {
        TbGamepublisher check = tbGamepublisherMapper.selectById(tbGame.getPublisher());
        if(check==null){
            return R.fail("游戏发行商信息错误",null);
        }
        int i = tbGameMapper.insert(tbGame);
        return i==1?R.ok("新增成功",null):R.fail("新增失败",null);
    }

    @Override
    public R<TbGame> queryByKey(Integer id) {
        TbGame tbGame = tbGameMapper.selectById(id);
        return tbGame == null ? R.fail("查询失败",null) :R.ok("查询成功",tbGame);
    }

    @Override
    public R<String> update(TbGame tbGame) {
        // 验证游戏发行商信息是否正确
        TbGamepublisher check = tbGamepublisherMapper.selectById(tbGame.getPublisher());
        if (check == null){
            return R.fail("软件类型信息错误",null);
        }
        int i = tbGameMapper.updateById(tbGame);
        return i==1?R.ok("修改成功",null):R.fail("修改失败",null);
    }

    @Override
    public R<String> delete(Integer id) {
        int i = tbGameMapper.deleteById(id);
        return i==1?R.ok("删除成功",null):R.fail("删除失败",null);
    }

    @Override
    public R<PageVo<TbGame>> query(TbGame tbGame, PageBean pageBean) {
        IPage<TbGame> page = new Page<>(pageBean.getPageNumber(),pageBean.getPageSize());
        QueryWrapper<TbGame> wrapper = new QueryWrapper<>();
        wrapper.eq(tbGame.getPublisher()!=null,"publisher",tbGame.getPublisher());
        wrapper.like(StringUtils.hasText(tbGame.getGname()),"gname",tbGame.getGname());
        wrapper.like(StringUtils.hasText(tbGame.getIntro()),"intro",tbGame.getIntro());
        page = tbGameMapper.selectPage(page,wrapper);
        return R.ok(page);
    }
}
